package com.lianwei.service.impl;

import com.lianwei.constant.CacheKey;
import com.lianwei.enums.SendCodeEnum;
import com.lianwei.enums.UserCodeEnum;
import com.lianwei.service.MailService;
import com.lianwei.service.NotifyService;
import com.lianwei.util.CheckUtil;
import com.lianwei.util.CommonUtil;
import com.lianwei.util.DateUtil;
import com.lianwei.util.JsonData;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/*
 *@ClassName NotifyServiceImpl
 *@Description 验证码服务
 *@Author Kuiwen.Sun
 *@Date 2022/1/11 13:46
 *@Version 1.0
 */
@Service
public class NotifyServiceImpl implements NotifyService {
    @Autowired
    private MailService mailService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final long MAIL_CODE_EXPIRED = 60 * 1000 * 10;

    private static final String subject = "注册EES商城";

    private static final String content = "您的EES商城验证码【%s】,打死不能告诉别人！";

    @Override
    public JsonData sendEmailCode(SendCodeEnum sendCodeEnum, String emailAddress) {
        String cachekey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), emailAddress);
        if (CheckUtil.isEmail(emailAddress)){
           //生成邮箱验证码
            String code = CommonUtil.getRandomCode(6);
            //以当前时间作为时间戳 60秒内不重发
            Long nowDateCurrentTime = DateUtil.getCurrentTimeMillis();
            Object getRedisByMailValue = redisTemplate.opsForValue().get(cachekey);
            if (getRedisByMailValue!=null){
                long reTime = DateUtil.getDistanceTime(Long.parseLong(getRedisByMailValue.toString().split("_")[1]),System.currentTimeMillis());
                if (reTime<60){
                    return  JsonData.buildResult(UserCodeEnum.CODE_LIMITED);
                }
            }
            redisTemplate.opsForValue().set(cachekey,code+"_"+nowDateCurrentTime,MAIL_CODE_EXPIRED, TimeUnit.MILLISECONDS);
            mailService.sendEmail(emailAddress,subject,String.format(content,code));
            return JsonData.buildSuccess(null,"邮件发送成功");
        }
        return  JsonData.buildResult(UserCodeEnum.CODE_LIMITED);
    }

    @Override
    public boolean checkEmailCode(SendCodeEnum sendCodeEnum, String emailAddress, String code) {
        String cachekey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), emailAddress);
        Object cacheValueForObj = redisTemplate.opsForValue().get(cachekey);
        String cacheValue = cacheValueForObj==null?null:cacheValueForObj.toString();
        if (StringUtil.isNotBlank(cachekey)){
           String cacheCode = cacheValue.split("_")[0];
           if (cacheCode.equals(code)){
               redisTemplate.delete(cachekey);
               return true;
           }
        }

        return false;
    }
}
